package org.egedede.commons.ui;

import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.util.ResourceBundle;

import javax.swing.JComponent;
import javax.swing.JLabel;

public class GridBagLayoutBuilder {

	private static final Insets DEFAULT_INSET = new Insets(5, 5, 5, 5);
	private static final int DEFAULT_FILL = GridBagConstraints.HORIZONTAL;
	private static final int DEFAULT_POSITION = GridBagConstraints.CENTER;
	private static final int DEFAULT_WIDTH = 1;
	private static final int DEFAULT_HEIGHT = 1;
	private static final double DEFAULT_WEIGHT_WIDTH = 0;
	private static final double DEFAULT_WEIGHT_HEIGHT = 0;

	private final JComponent comp;
	private final ResourceBundle bundle;

	private final GridBagConstraints gdc = new GridBagConstraints(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT,
			DEFAULT_WEIGHT_WIDTH, DEFAULT_WEIGHT_HEIGHT, DEFAULT_POSITION, DEFAULT_FILL, DEFAULT_INSET, 5, 5);

	public GridBagLayoutBuilder(final JComponent comp, final ResourceBundle bundle) {
		this.comp = comp;
		this.bundle = bundle;
	}

	public void addXY(final JComponent item, final int x, final int y) {
		gdc.gridx = x;
		gdc.gridy = y;
		comp.add(item, gdc);
		this.reset();
	}

	public void addXYWH(final JComponent item, final int x, final int y, final int width, final int height) {
		gdc.gridx = x;
		gdc.gridy = y;
		gdc.gridwidth = width;
		gdc.gridheight = height;
		comp.add(item, gdc);
		this.reset();
	}

	public void addXYLabel(final String label, final int x, final int y) {
		gdc.gridx = x;
		gdc.gridy = y;
		comp.add(new JLabel(bundle == null ? label : bundle.getString(label)), gdc);
		this.reset();
	}

	public void addXYWHLabel(final String label, final int x, final int y, final int width, final int height) {
		gdc.gridx = x;
		gdc.gridy = y;
		gdc.gridwidth = width;
		gdc.gridheight = height;
		comp.add(new JLabel(bundle == null ? label : bundle.getString(label)), gdc);
		this.reset();
	}

	public GridBagLayoutBuilder setAnchor(final int anchor) {
		gdc.anchor = anchor;
		return this;
	}

	public GridBagLayoutBuilder setFill(final int fill) {
		gdc.fill = fill;
		return this;
	}

	public GridBagLayoutBuilder setInsets(final Insets in) {
		gdc.insets = in;
		return this;
	}

	public GridBagLayoutBuilder setWeight(final double weightx, final double weighty) {
		gdc.weightx = weightx;
		gdc.weighty = weighty;
		return this;
	}

	private void reset() {
		gdc.anchor = DEFAULT_POSITION;
		gdc.fill = DEFAULT_FILL;
		gdc.gridheight = DEFAULT_HEIGHT;
		gdc.gridwidth = DEFAULT_WIDTH;
		gdc.insets = DEFAULT_INSET;
		gdc.weightx = DEFAULT_WEIGHT_WIDTH;
		gdc.weighty = DEFAULT_WEIGHT_HEIGHT;
	}
}
